﻿ /* $RCSFile: CrmEditISV.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/CrmEditISV/CrmEditISV.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:19  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:48  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:24  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;  
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Data.SqlClient;
using System.Web.Services.Protocols;
using System.Globalization;

using AddonNice.Core;
using AddonNice.UI;
using AddonNice.Design;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings;

using AddonNice.CRMWrapper;
using CrmSdk;
using CrmSdk.CRM4;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;
using System.IO;


namespace AddonNice.PageModules.CrmEditISV
{

    public class AStr
    {
        public const string Backup                  =   "CRM_EDITISV_BACKUP";
    }

    
    /// <summary>
    /// Initializer class for CrmEditISV 
    /// </summary>
    public class CrmEditISVSI : PortalCRMModuleControlSI
    {
        public CrmEditISVSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmEditISVSI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmEditISVSI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmEditISVSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);
            string extgrp                       =   pm.ExtendedResourcesGroup;

            SettingItemSpecial ShowContacts     =   new SettingItemSpecial(AStr.Backup,new BooleanDataType());
            ShowContacts.Value                  =   StStr.strTrue;
            ShowContacts.Order                  =   10;
            ShowContacts.ExtendedGroupName      =   extgrp;
            ShowContacts.EnglishName            =   "Backup before save";
            ShowContacts.Description            =   "Backup all customizations before saving changes.";
            bSettings.AddSetting(ShowContacts);

            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmEditISVSI InitSettings END.",ModuleTraceSwitch.Sw.Info);
        }
    }

    public partial class CrmEditISV : PortalCRMModuleControl
    {

        /// <summary>
        /// No entity needed here
        /// </summary>
        public override bool NeedAttachedEntity
        {
            get
            {
                return false;
            }
        }

        #region General implementation

        public override bool AdminModule
        {
            get
            {
                return true;
            }
        }

        public override Guid GuidID
        {
            get
            {
                return new Guid("{03AD4634-605B-45b7-9130-48A110855014}");
            }
        }
        #endregion General implementation


        public CrmEditISV()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CrmEditISV Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CrmEditISV Ctor END.",ModuleTraceSwitch.Sw.Info);
        }

        public override string ExtendedResourcesGroup 
		{
            get
            {
                const string extgrp                 =   "CRMEDITISV";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new CrmEditISVSI(bSettings,this);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // will be enabled by opening the file
                updateBtn.Enabled   =   false;
            }

        }

        void LoadISVConfig()
        {
            CrmUtil4ISV util        =   new CrmUtil4ISV((CrmWrapper4)Wrapper);
            string strSiteMap       =   util.ExportXml(); 
            TbISVConfig.Text        =   XmlValidator.FormatXml(strSiteMap);
        }

        void OpenBtn_Click(object sender, ImageClickEventArgs e)
        {
                LoadISVConfig();
                updateBtn.Enabled   =   true;
        }

        public string ValidateIsvConfigXml(string xml)
        {
            try 
            {
                string pagePath             =   Server.MapPath(Request.Url.AbsolutePath);
                FileInfo pageFile           =   new FileInfo(pagePath);
                string schemaPath           =   System.IO.Path.Combine(pageFile.Directory.FullName, "isv.config.xsd");

                XmlValidator validator      =   new XmlValidator(schemaPath);
                return   validator.Validate(xml);
            }
            catch (Exception ex) 
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmEditISV ValidateIsvConfigXml ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
        }

        void SetError(string errMSg)
        {
            lblErr.Text         =   errMSg;
            lblErr.CssClass     =   "Error";
        }

        void CrmEditISV_ADNUpdateModule(object sender, ModuleEventArgs e)
        {
            const string path = "//ImportExportXml/IsvConfig";
            try
            {
                XmlDocument metadata    =   new XmlDocument();
                metadata.LoadXml(TbISVConfig.Text);
                XmlNode nd              =   metadata.SelectSingleNode(path);
                string errMSg           =   ValidateIsvConfigXml(nd.InnerXml);
                if ( !string.IsNullOrEmpty(errMSg) )
                {
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEditISV CrmEditISV_ADNUpdateModule Page not valid Msg: {0}",errMSg),ModuleTraceSwitch.Sw.Info);
                    e.Cancel            =   true;
                    SetError(errMSg);
                    return;
                }
                bool backup             =   Settings[AStr.Backup].ToBool();
                bool ret                =   false;
                if ( backup )
                {
                    ret                 =   Wrapper.Util.BackupCustomizations();
                    if ( CRMTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmUtil4ISV UpdateISVConfig BackupCustomizations success: {0}.",ret),CRMTraceSwitch.Sw.Info);
                    // failed, we can't continue without backup
                    if ( !ret )
                    {
                        string msg      =   "[E]CrmUtil4ISV UpdateISVConfig BackupCustomizations failed, stopping save.";
                        if ( CRMTraceSwitch.Sw.TraceError )
                            Trace2.WriteLine(msg,CRMTraceSwitch.Sw.Info);
                        SetError(LocalizeHelper.Localize("CRM_BACKUP_ERR","Error in backup"));
                        e.Cancel            =   true;
                        return;
                    }
                }
                
                CrmUtil4ISV util        =   new CrmUtil4ISV((CrmWrapper4)Wrapper);
                ret                     =   util.UpdateISVConfig(TbISVConfig.Text,true);
                if ( !ret)
                {
                    
                    StringBuilder sb    =   new StringBuilder();
                    sb.AppendFormat("Error: {0}",util.errMsg);
                    SetError(sb.ToString());
                    e.Cancel            =   true;
                    return;
                }
                lblErr.Text             =   string.Format("Update Ok {0}",DateTime.Now);

            }
            catch (SoapException sex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmEditISV CrmEditISV_ADNUpdateModule soap ex :{0}", sex), ModuleTraceSwitch.Sw.Info);
                StringBuilder sb        =   new StringBuilder();
                sb.AppendFormat("Error: <br />{0}<br />",ErrorCodes.GetErrorMessage(sex));
                SetError(sb.ToString());
                e.Cancel                =   true;
                return;
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmEditISV CrmEditISV_ADNUpdateModule ex :{0}", ex), ModuleTraceSwitch.Sw.Info);
                throw;
            }
        }
        /// <summary>
        /// Triggered from Page.OnPreInit
        /// We must set the Add button before buttons are initialized by base method
        /// </summary>
        public override void Page_PreInit(object sender, EventArgs e)
        {
            base.Page_PreInit(sender, e);
            string strcult      =   Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
            updateBtn.SkinID    =   "Update_" + strcult;
            OpenBtn.SkinID      =   "Open_" + strcult;
        }


        #region Std overrides

        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            Load                                +=  new System.EventHandler(this.Page_Load);
            ADNUpdateModule                            +=  new PortalModuleEventHandler(CrmEditISV_ADNUpdateModule);
            OpenBtn.Click                       +=  new ImageClickEventHandler(OpenBtn_Click);
        }

        #endregion Std overrides
 
    }
}